#include "serial_command_handler.h"

SerialCommandHandler::SerialCommandHandler(
    CommandExecutor* executor,
    MQTTManager* mqtt,
    bool* drawingPaused,
    QueueHandle_t cmdQueue,
    SemaphoreHandle_t serialMtx
) : commandExecutor(executor), mqttManager(mqtt), isDrawingPaused(drawingPaused),
    commandQueue(cmdQueue), serialMutex(serialMtx) {
    
    // 初始化命令映射表
    initializeCommandMappings();
    
    Serial.println("✅ SerialCommandHandler 优化版初始化完成");
}

void SerialCommandHandler::initializeCommandMappings() {
    commandMappings = {
        // 基础命令
        {"help", [this](const String& cmd) { handleBasicCommands(cmd); }, "显示帮助信息"},
        {"h", [this](const String& cmd) { handleBasicCommands(cmd); }, "显示帮助信息"},
        {"status", [this](const String& cmd) { handleBasicCommands(cmd); }, "显示系统状态"},
        {"s", [this](const String& cmd) { handleBasicCommands(cmd); }, "显示系统状态"},
        
        // 运动控制命令
        {"start", [this](const String& cmd) { handleMotionCommands(cmd); }, "开始绘图"},
        {"stop", [this](const String& cmd) { handleMotionCommands(cmd); }, "停止绘图"},
        {"home", [this](const String& cmd) { handleMotionCommands(cmd); }, "回零"},
        {"enable", [this](const String& cmd) { handleMotionCommands(cmd); }, "启用电机"},
        {"disable", [this](const String& cmd) { handleMotionCommands(cmd); }, "禁用电机"},
        
        // 图案控制命令
        {"next", [this](const String& cmd) { handlePatternCommands(cmd); }, "下一个图案"},
        {"prev", [this](const String& cmd) { handlePatternCommands(cmd); }, "上一个图案"},
        {"list", [this](const String& cmd) { handlePatternCommands(cmd); }, "列出图案文件"},
        {"load", [this](const String& cmd) { handlePatternCommands(cmd); }, "加载图案文件"},
        
        // LED控制命令
        {"ledon", [this](const String& cmd) { handleLEDCommands(cmd); }, "启用LED灯带"},
        {"ledoff", [this](const String& cmd) { handleLEDCommands(cmd); }, "禁用LED灯带"},
        {"brightness", [this](const String& cmd) { handleLEDCommands(cmd); }, "设置全局亮度"},
        {"draweffect", [this](const String& cmd) { handleLEDCommands(cmd); }, "设置绘图效果"},
        {"drawcolor", [this](const String& cmd) { handleLEDCommands(cmd); }, "设置绘图颜色"},
        {"drawbright", [this](const String& cmd) { handleLEDCommands(cmd); }, "设置绘图亮度"},
        {"drawspeed", [this](const String& cmd) { handleLEDCommands(cmd); }, "设置绘图速度"},
        {"drawstatus", [this](const String& cmd) { handleLEDCommands(cmd); }, "显示LED状态"},
        
        // 系统监控命令
        {"taskinfo", [this](const String& cmd) { handleSystemCommands(cmd); }, "显示任务信息"},
        {"coreinfo", [this](const String& cmd) { handleSystemCommands(cmd); }, "显示核心信息"},
        {"meminfo", [this](const String& cmd) { handleSystemCommands(cmd); }, "显示内存信息"},
        {"position", [this](const String& cmd) { handleSystemCommands(cmd); }, "显示当前位置"},
        {"motorstatus", [this](const String& cmd) { handleSystemCommands(cmd); }, "显示电机状态"}
    };
}

CommandExecutor* SerialCommandHandler::getCommandExecutor() {
    return commandExecutor;
}

void SerialCommandHandler::handleSerialInput() {
    if (Serial.available()) {
        String command = Serial.readString();
        command.trim();
        
        if (command.length() > 0) {
            logCommand(command);
            processCommand(command);
        }
    }
}

void SerialCommandHandler::processCommand(const String& command) {
    if (command.isEmpty()) return;
    
    // 解析命令和参数
    int spaceIndex = command.indexOf(' ');
    String cmd = (spaceIndex > 0) ? command.substring(0, spaceIndex) : command;
    String params = (spaceIndex > 0) ? command.substring(spaceIndex + 1) : "";
    
    cmd.toLowerCase();
    
    // 查找并执行映射的命令
    for (const auto& mapping : commandMappings) {
        if (mapping.command == cmd) {
            mapping.handler(command);
            return;
        }
    }
    
    // 处理带参数的复合命令
    executeCommand(cmd, params);
}

void SerialCommandHandler::executeCommand(const String& cmd, const String& params) {
    int result = 0;
    
    if (cmd == "move") {
        auto values = parseParameters(params);
        if (values.size() >= 2) {
            result = commandExecutor->moveTo(values[0].toFloat(), values[1].toFloat());
            handleError(result, "移动到指定位置");
        } else {
            Serial.println("❌ 用法: move <theta> <rho>");
        }
    } else if (cmd == "moveto") {
        auto values = parseParameters(params);
        if (values.size() >= 2) {
            result = commandExecutor->moveToSteps(values[1].toInt(), values[0].toInt());
            handleError(result, "移动到指定步数");
        } else {
            Serial.println("❌ 用法: moveto <r_steps> <a_steps>");
        }
    } else if (cmd == "setspeed") {
        if (params.length() > 0) {
            result = commandExecutor->setDrawingSpeed(params.toFloat());
            handleError(result, "设置绘图速度");
        } else {
            Serial.println("❌ 用法: setspeed <速度>");
        }
    } else if (cmd == "setaccel") {
        if (params.length() > 0) {
            result = commandExecutor->setAcceleration(params.toFloat());
            handleError(result, "设置加速度");
        } else {
            Serial.println("❌ 用法: setaccel <加速度>");
        }
    } else if (cmd == "getspeed") {
        // 显示运动参数信息
        Serial.println("=== 绘图速度信息 ===");
        Serial.println("💡 使用 'setspeed <速度>' 调整绘图速度");
        Serial.println("💡 使用 'setaccel <加速度>' 调整加速度");
    } else if (cmd == "compensation") {
        if (params.length() > 0) {
            float comp = params.toFloat();
            if (comp >= 0.0 && comp <= 1.0) {
                result = commandExecutor->setCompensationFactor(comp);
                handleError(result, "设置补偿系数");
            } else {
                Serial.println("❌ 补偿系数范围: 0.0-1.0");
            }
        } else {
            Serial.println("❌ 用法: compensation <系数>");
        }
    } else if (cmd == "rotsteps") {
        if (params.length() > 0) {
            long steps = params.toInt();
            if (steps > 0 && steps <= 1000000) {
                result = commandExecutor->setRotationStepsPerRev(steps);
                handleError(result, "设置旋转轴步数");
            } else {
                Serial.println("❌ 步数范围: 1-1000000");
            }
        } else {
            Serial.println("❌ 用法: rotsteps <步数>");
        }
    } else if (cmd == "radsteps") {
        if (params.length() > 0) {
            long steps = params.toInt();
            if (steps > 0 && steps <= 500000) {
                result = commandExecutor->setRadiusMaxSteps(steps);
                handleError(result, "设置半径轴步数");
            } else {
                Serial.println("❌ 步数范围: 1-500000");
            }
        } else {
            Serial.println("❌ 用法: radsteps <步数>");
        }
    } else if (cmd == "automanage") {
        if (params.length() > 0) {
            String param = params;
            param.toLowerCase();
            bool enabled = (param == "on" || param == "true" || param == "1");
            result = commandExecutor->executeAutoManageCommand(enabled);
        } else {
            Serial.println("❌ 用法: automanage <on/off>");
        }
    } else if (cmd == "timeout") {
        if (params.length() > 0) {
            result = commandExecutor->executeTimeoutCommand(params.toInt());
        } else {
            Serial.println("❌ 用法: timeout <秒数>");
        }
    } else if (cmd == "resetmemory" || cmd == "clearmemory") {
        result = commandExecutor->executeResetMemoryCommand();
        handleError(result, "清除图案记忆");
    } else if (cmd == "showmemory" || cmd == "lastpattern") {
        result = commandExecutor->executeShowMemoryCommand();
    } else if (cmd == "deletejson") {
        result = commandExecutor->executeDeleteJsonCommand();
        if (result != 0) {
            if (result == 1) {
                Serial.println("💡 请检查SD卡连接状态");
            } else if (result == 2) {
                Serial.println("💡 请检查SD卡是否写保护或文件是否被占用");
            }
        }
    } else {
        Serial.printf("❌ 未知命令: %s，输入 'help' 查看可用命令\n", cmd.c_str());
    }
}

void SerialCommandHandler::handleBasicCommands(const String& command) {
    String cmd = command;
    cmd.toLowerCase();
    
    if (cmd == "help" || cmd == "h") {
        commandExecutor->executeHelpCommand();
    } else if (cmd == "status" || cmd == "s") {
        commandExecutor->executeDetailedStatusCommand();
    }
}

void SerialCommandHandler::handleMotionCommands(const String& command) {
    String cmd = command;
    cmd.toLowerCase();
    int result = 0;
    
    if (cmd == "start") {
        result = commandExecutor->executeStartCommand();
        handleError(result, "开始绘图");
        if (result == 1) {
            Serial.println("💡 GPIO17按钮: 短按切换start/stop, 长按3秒启用系统");
        } else if (result == 2) {
            Serial.println("💡 请将.thr图案文件放入SD卡，或使用 'load <文件名>' 手动加载");
        }
    } else if (cmd.startsWith("start ")) {
        String param = cmd.substring(6);
        if (param == "new") {
            if (isDrawingPaused) *isDrawingPaused = false;
            result = commandExecutor->executeStartCommand();
            handleError(result, "开始新绘图");
        }
    } else if (cmd == "stop") {
        result = commandExecutor->executeStopCommand();
        handleError(result, "停止绘图");
    } else if (cmd == "home") {
        result = commandExecutor->executeHomeCommand();
        handleError(result, "回零");
    } else if (cmd == "enable") {
        result = commandExecutor->enableMotors();
        handleError(result, "启用电机");
    } else if (cmd == "disable") {
        result = commandExecutor->disableMotors();
        handleError(result, "禁用电机");
    }
}

void SerialCommandHandler::handlePatternCommands(const String& command) {
    String cmd = command;
    cmd.toLowerCase();
    int result = 0;
    
    if (cmd == "next") {
        result = commandExecutor->executeNextCommand();
        if (result == 0) {
            Serial.println("✅ 已切换到下一个图案");
            result = commandExecutor->executeStartCommand();
            handleError(result, "开始绘制新图案");
        } else {
            handleError(result, "切换下一个图案");
        }
    } else if (cmd == "prev" || cmd == "pre") {
        result = commandExecutor->executePrevCommand();
        if (result == 0) {
            Serial.println("✅ 已切换到上一个图案");
            result = commandExecutor->executeStartCommand();
            handleError(result, "开始绘制新图案");
        } else {
            handleError(result, "切换上一个图案");
        }
    } else if (cmd == "list") {
        result = commandExecutor->executeListCommand();
        if (result != 0) {
            Serial.println("请检查:");
            Serial.println("- SD卡是否插入");
            Serial.println("- SD卡是否格式化为FAT32");
            Serial.println("- 接线是否正确 (SCK:18, MISO:19, MOSI:23, CS:5)");
        }
    } else if (cmd.startsWith("load ")) {
        String filename = cmd.substring(5);
        filename.trim();
        
        if (filename.length() == 0) {
            Serial.println("❌ 用法: load <文件名>");
            return;
        }
        
        result = commandExecutor->executeLoadCommand(filename);
        if (result == 0) {
            Serial.printf("✅ 图案文件 %s 加载成功\n", filename.c_str());
        } else {
            handleError(result, "加载图案文件");
            if (result == 1) {
                Serial.println("💡 SD卡未就绪，请检查SD卡连接");
            } else if (result == 2) {
                Serial.println("💡 文件不存在，使用 'list' 查看可用文件");
            }
        }
    }
}

void SerialCommandHandler::handleLEDCommands(const String& command) {
    String cmd = command;
    cmd.toLowerCase();
    int result = 0;
    
    if (cmd == "ledon") {
        result = commandExecutor->enableLED(true);
        handleError(result, "启用WS2812灯带");
    } else if (cmd == "ledoff") {
        result = commandExecutor->enableLED(false);
        handleError(result, "禁用WS2812灯带");
    } else if (cmd.startsWith("brightness ")) {
        String brightStr = cmd.substring(11);
        result = commandExecutor->setGlobalBrightness(brightStr.toInt());
        handleError(result, "设置全局亮度");
    } else if (cmd.startsWith("draweffect ")) {
        String effectStr = cmd.substring(11);
        result = commandExecutor->setDrawingEffect(effectStr.toInt());
        handleError(result, "设置绘图效果");
    } else if (cmd.startsWith("drawcolor ")) {
        String colorStr = cmd.substring(10);
        int r, g, b;
        if (parseColorParameters(colorStr, r, g, b)) {
            result = commandExecutor->setDrawingColor(r, g, b);
            handleError(result, "设置绘图颜色");
        } else {
            Serial.println("❌ 颜色格式错误，请使用: drawcolor r,g,b");
        }
    } else if (cmd.startsWith("drawbright ")) {
        String brightStr = cmd.substring(11);
        result = commandExecutor->setDrawingBrightness(brightStr.toInt());
        handleError(result, "设置绘图亮度");
    } else if (cmd.startsWith("drawspeed ")) {
        String speedStr = cmd.substring(10);
        result = commandExecutor->setDrawingSpeed(speedStr.toFloat());
        handleError(result, "设置绘图速度");
    } else if (cmd == "drawstatus") {
        String status = commandExecutor->getLEDStatus();
        Serial.println("📊 当前LED设置状态:");
        Serial.println(status);
    }
}

void SerialCommandHandler::handleSystemCommands(const String& command) {
    String cmd = command;
    cmd.toLowerCase();
    int result = 0;
    
    if (cmd == "taskinfo") {
        result = commandExecutor->executeTaskInfoCommand();
    } else if (cmd == "coreinfo") {
        result = commandExecutor->executeCoreInfoCommand();
    } else if (cmd == "meminfo") {
        result = commandExecutor->executeMemInfoCommand();
    } else if (cmd == "position") {
        result = commandExecutor->executePositionCommand();
    } else if (cmd == "motorstatus") {
        result = commandExecutor->executeMotorStatusCommand();
    }
    
    if (result != 0) {
        handleError(result, "系统信息查询");
    }
}

void SerialCommandHandler::handleError(int errorCode, const String& context) {
    if (errorCode != 0) {
        Serial.printf("❌ %s失败，错误码: %d\n", context.c_str(), errorCode);
    }
}

void SerialCommandHandler::logCommand(const String& command) {
    Serial.printf("🔍 命令: %s\n", command.c_str());
}

std::vector<String> SerialCommandHandler::parseParameters(const String& command) {
    std::vector<String> params;
    int start = 0;
    int end = command.indexOf(' ');
    
    while (end != -1) {
        params.push_back(command.substring(start, end));
        start = end + 1;
        end = command.indexOf(' ', start);
    }
    
    if (start < command.length()) {
        params.push_back(command.substring(start));
    }
    
    return params;
}

bool SerialCommandHandler::parseColorParameters(const String& params, int& r, int& g, int& b) {
    int commaIndex1 = params.indexOf(',');
    int commaIndex2 = params.lastIndexOf(',');
    
    if (commaIndex1 > 0 && commaIndex2 > commaIndex1) {
        r = params.substring(0, commaIndex1).toInt();
        g = params.substring(commaIndex1 + 1, commaIndex2).toInt();
        b = params.substring(commaIndex2 + 1).toInt();
        return true;
    }
    
    return false;
}

bool SerialCommandHandler::parseFloatParameters(const String& params, std::vector<float>& values) {
    values.clear();
    auto stringParams = parseParameters(params);
    
    for (const auto& param : stringParams) {
        values.push_back(param.toFloat());
    }
    
    return values.size() > 0;
}

// 兼容性方法
bool SerialCommandHandler::canExecuteMotorCommand(const String& command) {
    return commandExecutor->canExecuteMotorCommand(command);
}

void SerialCommandHandler::saveLastUsedPattern(const String& patternName) {
    if (commandExecutor) {
        commandExecutor->saveLastUsedPattern(patternName);
    }
}

String SerialCommandHandler::loadLastUsedPattern() {
    if (commandExecutor) {
        return commandExecutor->loadLastUsedPattern();
    }
    return "";
}

bool SerialCommandHandler::loadDefaultOrLastPattern() {
    int result = commandExecutor->loadDefaultOrLastPattern();
    return (result == 0);
}

void SerialCommandHandler::handleShortPressStartStop() {
    Serial.println("🔄 短按Start/Stop切换功能");
    // 委托给CommandExecutor处理
    if (commandExecutor) {
        // 假设CommandExecutor有相应的方法处理短按功能
        // commandExecutor->handleShortPressStartStop();
    }
}